package com.example.addressdemo;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AlphabetIndexer;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.example.addressdemo.Address.Contact;
import com.example.addressdemo.DB.DBAdapter;

/**
 * Created by 十田田 on 2021/5/31.
 */

public class OrderAdapter extends BaseAdapter
{
    private Contact[] contacts;//接收根据字母排序好了的contact
    private LayoutInflater inflater;//布局填充器，加载ListView子布局
    private AlphabetIndexer indexer;//AlphabetIndexer字母索引辅助类
    private DBAdapter dbAdapter;

    public OrderAdapter(Context context, Contact[] contacts, AlphabetIndexer indexer)
    {
        this.contacts = contacts;
        inflater = LayoutInflater.from(context);
        this.indexer = indexer;
    }
    @Override
    public int getCount() {
        return contacts.length;
    }

    @Override
    public Contact getItem(int position) {
        return contacts[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null)
        {
            convertView = inflater.inflate(R.layout.item_main, parent, false);
            holder = new ViewHolder();
            //holder.Letter = (TextView) convertView.findViewById(R.id.Letter_item);
           // holder.Name = (TextView) convertView.findViewById(R.id.Name_item);
            convertView.setTag(holder);
        }
        else
        {
            holder = (ViewHolder) convertView.getTag();
        }
        Contact contact=contacts[position];
        holder.Name.setText(contact.name);
        //获取这个位置代表的字符在字符表中的位置
        int section = indexer.getSectionForPosition(position);
        //判断当前位置是否是第一个出现这个字符，indexer.getPositionForSection(section)获取第一次出现的位置
        if (position == indexer.getPositionForSection(section))
        {
            holder.Letter.setVisibility(View.VISIBLE);
            holder.Letter.setText(contact.name.substring(0,1));
        }
        else
        {
            holder.Letter.setVisibility(View.GONE);
        }
        return convertView;
    }
    private class ViewHolder
    {
        TextView Letter;
        TextView Name;
    }
}